import React, { Component } from 'react';
import { Text, View, Slider, Alert, Button, AsyncStorage } from 'react-native';
import Sound from 'react-native-sound';

export default class PlayBar extends Component {
    constructor() {
        super();
        this.state = {
            playing: false, //playing, paused
            duration: 0
        }
        this.sliderEditing = false;
    }
    componentDidMount() {
        this.timeout = setInterval(() => {
            if (this.sound && this.sound.isLoaded() && this.state.playing && !this.sliderEditing) {
                this.sound.getCurrentTime((seconds, isPlaying) => {
                    this.props.report(seconds)
                })
            }
        }, 1000);
    }
    getAudioTimeString = (seconds) => {
        const h = parseInt(seconds / (60 * 60));
        const m = parseInt(seconds % (60 * 60) / 60);
        const s = parseInt(seconds % 60);

        return ((h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s));
    }
    onSliderEditStart = () => {
        this.sliderEditing = true;
    }
    onSliderEditEnd = () => {
        this.sliderEditing = false;
    }
    onSliderEditing = value => {
        if (this.sound) {
            this.sound.setCurrentTime(value);
            this.setState({ seconds: value });
        }
    }
    play = async () => {
        if (this.sound) {
            this.sound.play(this.playComplete);
            this.setState({ playing: true });
        }
    }
    release() {
        if (this.sound) {
            this.sound.release();
            this.sound = null;
        }
    }
    setSound = async () => {
        this.setState({
            playing: false
        })
        if (this.sound) {
            this.sound.release()
        }

        this.sound = new Sound(this.props.path, '', (error, props) => {
            if (error) {
                console.log('failed to load the sound', error);
                Alert.alert('Notice', 'audio file error. (Error code : 1)');
                this.setState({ playing: false });
                this.sound.release();
                this.sound = null;
            } else {
                this.setState({ playing: false, duration: props.duration });
                this.sound.setCurrentTime(this.props.seconds);
            }
        });
    }
    playComplete = (success) => {
        if (this.sound) {
            if (success) {
                console.log('successfully finished playing');
            } else {
                console.log('playback failed due to audio decoding errors');
                Alert.alert('Notice', 'audio file error. (Error code : 2)');
            }
            this.setState({ playing: false });
            this.props.report(0)
            this.sound.setCurrentTime(0);
        }
    }
    pause = () => {
        if (this.sound) {
            this.sound.pause();
        }

        this.setState({ playing: false });
    }
    render() {
        const currentTimeString = this.getAudioTimeString(this.props.seconds);
        const durationString = this.getAudioTimeString(this.state.duration);
        return (
            <View style={{ backgroundColor: "black" }}>
                <View style={{ marginHorizontal: 15, marginTop: 15 }}>
                    <Text style={{ color: "white" }}>{this.props.path}</Text>
                </View>
                <View style={{ marginVertical: 15, marginHorizontal: 15, flexDirection: 'row' }}>
                    <Text style={{ color: 'white', alignSelf: 'center' }}>{currentTimeString}</Text>
                    <Slider
                        onTouchStart={this.onSliderEditStart}
                        // onTouchMove={() => console.log('onTouchMove')}
                        onTouchEnd={this.onSliderEditEnd}
                        // onTouchEndCapture={() => console.log('onTouchEndCapture')}
                        // onTouchCancel={() => console.log('onTouchCancel')}
                        onValueChange={this.onSliderEditing}
                        value={this.props.seconds} maximumValue={this.state.duration} maximumTrackTintColor='gray' minimumTrackTintColor='white' thumbTintColor='white'
                        style={{ flex: 1, alignSelf: 'center' }} />
                    <Text style={{ color: 'white', alignSelf: 'center' }}>{durationString}</Text>
                    <View style={{ paddingLeft: 15 }}>
                        {this.state.playing == true &&
                            <Button onPress={this.pause} title="暂停">
                            </Button>}
                        {this.state.playing == false &&
                            <Button onPress={this.play} title="开始">
                            </Button>}
                    </View>
                </View>
            </View>
        )
    }
}